package com.mf.basic.config;

import cn.dev33.satoken.stp.StpInterface;
import com.mf.basic.entity.DtoPermission;
import com.mf.basic.entity.DtoRole;
import com.mf.basic.services.ServicePermission;
import com.mf.basic.services.ServiceRole;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Luke on 2025/3/7 16:12.
 */
@Component
public class ConfigSaToken implements StpInterface {

    @Resource
    private ServicePermission servicePermission;
    @Resource
    private ServiceRole serviceRole;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        long userId = 0L;
        final List<String> x = verifyPermission(userId, loginId);
        if (x != null) {
            return x;
        }
        List<DtoPermission> permissionList = servicePermission.getBaseMapper().listByUserId(userId);
        if (CollectionUtils.isEmpty(permissionList)) {
            return new ArrayList<>();
        }
        return permissionList.stream().map(DtoPermission::getPermName).toList();
    }

    private List<String> verifyPermission(long userId, Object loginId) {
        if (loginId == null) {
            return new ArrayList<>();
        }

        try {
            userId = Long.parseLong(loginId.toString());
        } catch (Exception e) {
            return new ArrayList<>();
        }
        if (userId == 1) {
            return List.of("*");
        }
        return null;
    }

    /**
     * 根据账号id查询角色集合
     *
     * @param loginId 账号id
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {

        long userId = 0L;
        final List<String> x = verifyPermission(userId, loginId);
        if (x != null) return x;
        List<DtoRole> roleList = serviceRole.getBaseMapper().selectRolesByUserId(userId);
        if (CollectionUtils.isEmpty(roleList)) {
            return new ArrayList<>();
        }
        return roleList.stream().map(DtoRole::getRoleName).toList();
    }
}
